#!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on 2017年8月21日

@author: dayu
'''
from Tkinter import *
from JGListCreator import JGListCreator as Creator
import time
import threading 

class JgUI(Frame):
    '''
    classdocs
    '''


    def __init__(self, master=None):
        '''
        Constructor
        '''
        Frame.__init__(self, master)
        self.pack()
        
        self.entry81 = [] # 81个输入控件
        self.jg81 = []    # 81个输入控件对应的数据
        self.posList = [] # 已经被预先填入九宫格的数据列表  以行划分，每个填入的数字将以 数字：位置 这样的键值对记录
        self.ridList = [] # 每列已经被用过的数字记录列表，以列划分，每个填入的数字将以 数字：位置 这样的键值对记录
        self.seqList = [] # 每行所有可能序列对象，JGListCreator对象，每个对象对应一行，共九个

        
        self.createValueMatrix() # 初始化数据模型中的81个数据 IntVar
        self.create81Entry()     # 初始化81个输入控件
#         self.jg81[3][4].set('8')
        
        self.createButton()
        
    def testClick(self):
#         self.set9BgColor(4, 'red')
        self.commitPosMap()
        print self.posList
        data = [1,3,2,4,5,6,7,8,9]
        self.fillListToJgGraph(5, data)
        
    def startProcess(self):
        '''
        开始执行
        '''
        self.commitPosMap()  # 1.记录预定填入的数字
        self.createSeqList() # 2.生成最初的所有可能的序列列表，共9个
        #self.processOnce()
        th=threading.Thread(target=self.processOnce)  
        th.setDaemon(True)#守护线程  
        th.start() 
        return
    def processOnce(self):
        i = 0
        s = []
        while i < 9:
            s.append(self.seqList[i].serialization)
            i = i + 1
            #---------------------
        r = s[0][0]
        self.fillListToJgGraph(0, r)
        self.commitRidMap()
        
        for m in self.ridList :
            thList = []
            i = 1
            while i < 2 :
                thList.append(self.ridThread(s[i], m))
                i = i + 1
#             for th in thList :
#                 th.join()
        

            
        i = 0
        k = 0
        while k < 3 :
            i = k * 3
            while i < 3 + k * 3 :
                j = 0
                ridMap = {}
                while j < 3 :
                    ridMap[r[j + k * 3]] = i
                    j = j + 1
                self.ridThread(s[1], ridMap)
                self.ridThread(s[2], ridMap)
                i = i + 1
            k = k + 1
            #-----------------------------------
        if len(s[1]) < 1 :
            print '第二行已经没有数据'
            return
        
        r = s[1][0]
        self.fillListToJgGraph(1, r)
        self.commitRidMap()
        i = 2
        while i < 9 :
            for m in self.ridList :
                self.ridThread(s[i], m)
            i = i + 1
        i = 0
        k = 0
        while k < 3 :
            i = k * 3
            while i < 3 + k * 3 :
                j = 0
                ridMap = {}
                while j < 3 :
                    ridMap[r[j + k * 3]] = i
                    j = j + 1
                self.ridThread(s[2], ridMap)
                i = i + 1
            k = k + 1
            # -------------------------------------------
        if len(s[2]) < 1 :
            print '第三行已经没有数据'
            return
        
        r = s[2][0]
        self.fillListToJgGraph(2, r)
        self.commitRidMap()
        i = 3
        while i < 9 :
            for m in self.ridList :
                self.ridThread(s[i], m)
            i = i + 1
            # =====================================
            #--------------------- 2
        r = s[3][0]
        self.fillListToJgGraph(3, r)
        self.commitRidMap()
        i = 4
        while i < 9 :
            for m in self.ridList :
                self.ridThread(s[i], m)
            i = i + 1
        i = 0
        k = 0
        while k < 3 :
            i = k * 3
            while i < 3 + k * 3 :
                j = 0
                ridMap = {}
                while j < 3 :
                    ridMap[r[j + k * 3]] = i
                    j = j + 1
                self.ridThread(s[4], ridMap)
                self.ridThread(s[5], ridMap)
                i = i + 1
            k = k + 1
            #-----------------------------------
        if len(s[4]) < 1 :
            print '第5行已经没有数据'
            return
        
        r = s[4][0]
        self.fillListToJgGraph(4, r)
        self.commitRidMap()
        i = 5
        while i < 9 :
            for m in self.ridList :
                self.ridThread(s[i], m)
            i = i + 1
        i = 0
        k = 0
        while k < 3 :
            i = k * 3
            while i < 3 + k * 3 :
                j = 0
                ridMap = {}
                while j < 3 :
                    ridMap[r[j + k * 3]] = i
                    j = j + 1
                self.ridThread(s[5], ridMap)
                i = i + 1
            k = k + 1
            # -------------------------------------------
        if len(s[5]) < 1 :
            print '第6行已经没有数据'
            return
        
        r = s[5][0]
        self.fillListToJgGraph(5, r)
        self.commitRidMap()
        i = 6
        while i < 9 :
            for m in self.ridList :
                self.ridThread(s[i], m)
            i = i + 1
            # =====================================
            
                        #---------------------
        r = s[6][0]
        self.fillListToJgGraph(6, r)
        self.commitRidMap()
        i = 7
        while i < 9 :
            for m in self.ridList :
                self.ridThread(s[i], m)
            i = i + 1
        i = 0
        k = 0
        while k < 3 :
            i = k * 3
            while i < 3 + k * 3 :
                j = 0
                ridMap = {}
                while j < 3 :
                    ridMap[r[j + k * 3]] = i
                    j = j + 1
                self.ridThread(s[7], ridMap)
                self.ridThread(s[8], ridMap)
                i = i + 1
            k = k + 1
            #-----------------------------------
        if len(s[7]) < 1 :
            print '第8行已经没有数据'
            return
        
        r = s[7][0]
        self.fillListToJgGraph(7, r)
        self.commitRidMap()
        i = 1
        while i < 9 :
            for m in self.ridList :
                self.ridThread(s[i], m)
            i = i + 1
        i = 0
        k = 0
        while k < 3 :
            i = k * 3
            while i < 3 + k * 3 :
                j = 0
                ridMap = {}
                while j < 3 :
                    ridMap[r[j + k * 3]] = i
                    j = j + 1
                self.ridThread(s[8], ridMap)
                i = i + 1
            k = k + 1
            # -------------------------------------------
        if len(s[8]) < 1 :
            print '第9行已经没有数据'
            return
        
        r = s[8][0]
        self.fillListToJgGraph(8, r)
            # =====================================
            
        
    def createButton(self):
        button = Button(self)
        button['text'] = 'test'
        button.config(command = self.testClick)
        button.grid(row = 10, column = 5)
        button = Button(self)
        button['text'] = '开始'
        button.config(command = self.startProcess)
        button.grid(row = 10, column = 3)
        button.config(height = 3, width = 5)
        
    def createValueMatrix(self):
        '''
        与九宫81个格子相对应的数据
        '''
        i = 0
        j = 0
        while i < 9 :
            rowList = []
            self.jg81.append(rowList)
            while j < 9 :
                val = IntVar()
                rowList.append(val)
                j = j + 1
            i = i + 1
            j = 0
            
    def create81Entry(self):
        '''
        九宫格81个输入框
        '''
        
        i = 0
        j = 0
        while i < 9 :
            rowList = []
            self.entry81.append(rowList)
            while j < 9 :
                entry = Entry(self)
                entry.grid(row = i, column = j)
                entry.config(width = 1, font = ('Helvetica', '24', 'bold'), 
                             textvariable = self.jg81[i][j],
                             borderwidth = 26, relief = 'flat')
                rowList.append(entry)
                j = j + 1
            i = i + 1
            j = 0
        
    
    def set9BgColor(self, n ,color):
        '''
        工具方法：
        设置方形九宫格的背景颜色
        '''
        i = 0
        j = 0
        r = n / 3 
        c = n % 3 -1 
        print r, c
        while i < 3 :
            
            while j < 3 :
                row = i + r * 3
                col = j + c * 3
                entry = self.entry81[row][col]
#                 val = self.jg81[row][col]
#                 val.set(row * col)
                entry.config(fg = color)
                j = j + 1
            i = i + 1
            j = 0
        

    def commitPosMap(self):
        '''
        确认图上已经被填写了数字的格子
        一行一个map
        '''
        i = 0
        j = 0
        
        while i < 9 :
            posMap = {}
            self.posList.append(posMap)
            while j < 9 :
                
                val = self.jg81[i][j].get()
                
                if val > 0 and val < 10 :
                    posMap[val] = j
                
                j = j + 1
            i = i + 1
            j = 0
         
    def commitRidMap(self):
        '''
        已经用过的数在后续可能序列中剔除
        一列一个map
        '''
        i = 0
        j = 0
        self.ridList = [] # 请空
        while i < 9 :
            posMap = {}
            self.ridList.append(posMap)
            while j < 9 :
                
                val = self.jg81[j][i].get()
                
                if val > 0 and val < 10 :
                    posMap[val] = i
                
                j = j + 1
            i = i + 1
            j = 0   
    def fillListToJgGraph(self, row, data):
        '''
        将一个序列填入九宫格中的一行
        '''
        if len(data) != 9 or row < 0 or row >= 9:
            return
        i = 0 
        while i < 9 :
            self.jg81[row][i].set(data[i])
            i = i + 1
        time.sleep(0.001)
        
    def createSeqList(self):
        '''
        生成某一行所有可能的序列
        self.commitPosMap() 必需在之前已经被调用过
        '''    
        i = 0
        self.seqList = []  # 请空列表
        while i < 9 :
            self.seqList.append(Creator())
            creator = self.seqList[i]
            creator.hasFixNumbers(self.posList[i])
            i = i + 1
            
            
    def ridThread(self, delList, posMap):
        th = threading.Thread(target=self.ridSomeFormList, args=(delList, posMap,))
        th.start()   
        th.join()
        return th 
        
    def ridSomeFormList(self, delList, posMap):
        '''
        剔除位置已经被占用的序列
        posMap 已经被占用的数和位置
        '''
#         delList = self.serialization[:]
        retList = delList[:]
        for s in delList :
            for n in posMap :
                if s[posMap.get(n)] == n :
                    retList.remove(s)
                    print 'rid:', s
        return retList
    
    def verify(self, nine):
        '''
        校验一个列表是否为九宫格序列
        '''
        if len(nine) != 9 :
            return False
        normal = [1,2,3,4,5,6,7,8,9]
        for n in nine :
            if n not in normal :
                return False
            else :
                normal.remove(n)
        if len(normal) == 0 :
            return True
        else :
            return False
root = Tk()
app = JgUI(master=root)
app.master.title('九宫格')
app.mainloop()       